package com.tledu.springbootmybatis.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.tledu.springbootmybatis.core.exception.CustomException;
import com.tledu.springbootmybatis.domain.User;
import com.tledu.springbootmybatis.mapper.UserMapper;
import com.tledu.springbootmybatis.service.IUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author cyrus
 */
@Service
@AllArgsConstructor
public class UserServiceImpl implements IUserService {

    private final UserMapper userMapper;

    @Override
    public List<User> list(User user) {
        return userMapper.list(user);
    }

    @Override
    public void insert(User user) {
        if (StrUtil.isNotBlank(user.getPassword())) {
            user.setPassword(SecureUtil.md5(user.getPassword()));
        }
        int i = userMapper.insert(user);
    }

    @Override
    public void delete(Integer id) {
        userMapper.delete(id);
    }

    @Override
    public void update(User user) {
        if (StrUtil.isNotBlank(user.getPassword())) {
            user.setPassword(SecureUtil.md5(user.getPassword()));
        }
        userMapper.update(user);
    }

    @Override
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public User login(String username, String password) {
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            // 用户不存在
            throw new CustomException("用户不存在");
        }
        if (!SecureUtil.md5(password).equals(user.getPassword())) {
            throw new CustomException("密码不正确");
        }
        // 登录成功
        return user;
    }
}
